package com.andy.base.conn;

import com.andy.base.config.ServerConfig;
import com.andy.base.http.HttpProtocolUtil;
import com.andy.base.mapper.Engine;
import com.andy.base.mapper.Mapper;
import com.andy.base.mapper.MappingData;
import com.andy.base.servlet.Request;
import com.andy.base.servlet.Response;
import com.andy.base.servlet.Servlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class RequestProcessor extends Thread{

    private Engine engine;
    private ServerConfig serverConfig;
    private Socket socket;


    public RequestProcessor(Engine engine, ServerConfig serverConfig, Socket socket) {
        this.engine = engine;
        this.serverConfig = serverConfig;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            //将输入输出流封装为request和response
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            String url = request.getUrl();
            //把host交给责任链去获取host,context,wrapper
            MappingData mappingData = request.getMappingData();
            Mapper mapper = engine;
            while(mapper != null && mapper.needMapping()){
                mapper = mapper.map(url,mappingData);
            }
            //如果是静态文件，直接加载静态文件，不走servlet。 TODO 这里暂时只考虑html
            if(url.endsWith(".html")){
                String absoluteResourcePath = serverConfig.getAppBase()+ url;
                response.outputHtml(absoluteResourcePath);
            }else{
                //如果wrapper是null则404
                if(mappingData.getWrapper()==null){
                    response.output(HttpProtocolUtil.getHttpHeader404());
                }else{
                    //拿到servlet并调用
                    Servlet servlet = mappingData.getWrapper().getServlet();
                    servlet.service(request,response);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭tcp连接
            try {
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
